<template>
  <view class="wrap">
    <scroll-view
      class="scroll-X"
      scroll-x="true"
      :scroll-with-animation="true"
      :scroll-into-view="tabId"
    >
      <view class="headerUl">
        <view
          :id="'scroll_' + index"
          :class="['item', tabActive == index ? 'on' : '']"
          v-for="(item, index) in tabList"
          :key="index"
        >
          <img
            class="img"
            v-if="item.finished"
            src="https://ainengli.meilianshuke.com/jkhx/question-blend.png"
            alt=""
          />
          <view class="num" v-else> {{ item.num }} </view>
          <view class="name">{{ item.name }}</view>
          <text
            :class="['border', item.borderShow == true ? 'on' : '']"
            v-if="index < tabList.length - 1"
          ></text>
        </view>
      </view>
    </scroll-view>
    <scroll-view
      v-if="scrollXList && scrollXList.length > 0"
      :scroll-with-animation="true"
      @scroll="scrollX"
      :scroll-left="scrollLeft"
      class="scroll-X"
      scroll-x="true"
    >
      <view class="tabList">
        <view
          :class="['item', state.scrollxActive == index ? 'on' : '']"
          v-for="(item, index) in scrollXList"
          :key="index"
          @tap="tabFun(index, item)"
        >
          <text class="text">{{ item.name }}</text>
        </view>
      </view>
    </scroll-view>
    <view
      :class="[
        'questionWrap',
        (state.type == 'detail' && state.questionList && state.questionList.length > 1) ||
        state.type != 'detail'
          ? 'on'
          : ''
      ]"
    >
      <scroll-view
        @scroll="scroll"
        class="scroll-Y"
        scroll-y
        :scroll-into-view="scrollId"
        scroll-animation-duration="300"
        v-if="state.questionList.length > 0"
      >
        <indexQuestion
          :List="state.questionList[state.tabActive]?.list"
          ref="indexQuestionRef"
          class="my-question"
          :cWidth="cWidth"
          @change="onChange"
          :disabled="state.type === 'detail' || state.type === 'beOverdue' ? true : false"
        />
      </scroll-view>
    </view>
    <view
      v-if="
        (state.type == 'detail' && state.questionList && state.questionList.length > 1) ||
        state.type != 'detail'
      "
      :class="[
        'fixed',
        (state.type == 'detail' || state.type == 'beOverdue') &&
        state.questionList &&
        state.questionList.length &&
        tabActive + 1 == state.questionList.length &&
        state.questionList &&
        state.questionList.length > 1
          ? 'on'
          : ''
      ]"
    >
      <button class="pre_btn" v-if="tabActive != 0" @tap="prev">上一步</button>

      <template v-if="state.type == 'beOverdue'">
        <templete
          v-if="
            state.questionList &&
            state.questionList.length &&
            tabActive + 1 == state.questionList.length
          "
        >
        </templete>
        <button v-else class="next_btn" @tap="nextClick">
          {{
            state.questionList &&
            state.questionList.length &&
            tabActive + 1 == state.questionList.length
              ? '提交问卷'
              : '下一步'
          }}
        </button>
      </template>
      <template v-else>
        <button
          v-if="
            state.type != 'detail' ||
            (state.type == 'detail' && tabActive + 1 < state.questionList.length) ||
            state.type == 'beOverdue'
          "
          class="next_btn"
          @tap="nextClick"
        >
          {{
            state.questionList &&
            state.questionList.length &&
            tabActive + 1 == state.questionList.length
              ? '提交问卷'
              : '下一步'
          }}
        </button>
      </template>
    </view>
  </view>
</template>

<script setup lang="ts">
import { reactive, ref, nextTick, watch } from 'vue'
import { onShow, onLoad } from '@dcloudio/uni-app'
import { throttle, debounce, getPage } from '@/utils/tools'
import {
  questionnaire_save,
  follow_info,
  questionnaire_answer,
  questionnaireFollow_save
} from './fillin'
import indexQuestion from '@/module/components/MyQuestion/index.vue'
import {
  showCondition,
  next,
  validate,
  convert,
  fillValue
} from '@/module/components/MyQuestion/tools'

const indexQuestionRef = ref(null)
const cWidth = ref(uni.upx2px(750 - 128))
const tabActive = ref(0) //头部进度条
const tabId = ref('')
const state = reactive({
  userInfo: {},
  questionList: [],
  questionListOld: [],
  tabActive: 0, //问卷列表 第几个list
  scrollxActive: 0,
  questionInfo: {},
  questionInfoOld: {},
  id: '',
  type: ''
})
const scrollId = ref('')
const scrollLeft = ref(0)
const scrollXList = ref([])
const isClickTab = ref(false) // 新增标志位
const questionnaireId = ref('')
const questionnaireRecordId = ref('')
const tabList = ref([])

const relatives = ref(0)
watch(
  () => state.scrollxActive,
  (n, o) => {
    if (state.tabActive == 1) {
      if (n > 3) {
        scrollLeft.value = 380
      } else {
        scrollLeft.value = 0
      }
    } else if (state.tabActive == 2) {
      if (n >= 3) {
        scrollLeft.value = 372
      } else {
        scrollLeft.value = 0
      }
    }
  },
  { immediate: true, deep: true }
)
onLoad((option) => {
  state.type = option.type ? option.type : ''
  state.id = option.id ? option.id : ''
  questionnaireId.value = option.questionnaireId ? option.questionnaireId : ''
  questionnaireRecordId.value = option.questionnaireRecordId ? option.questionnaireRecordId : ''
  state.userInfo = uni.getStorageSync('userInfo') ? JSON.parse(uni.getStorageSync('userInfo')) : {}
  init()
})
const tabListFun = () => {
  for (let i = 0; i < tabList.value.length; i++) {
    tabList.value[i].borderShow = false
    tabList.value[i].finished = false
    if (i < tabActive.value) {
      tabList.value[i].borderShow = true
      tabList.value[i].finished = true
    }
  }
}
const init = async () => {
  if (state.type == 'detail') {
    const params = {
      questionnaireRecordId: questionnaireRecordId.value,
      empi: state.userInfo.patientInfo.empi
    }
    await questionnaire_answer(params).then((res) => {
      if (res && res.data) {
        let answer = res.data.patientQuestionnaireAnswerVO
        let questionList = JSON.parse(res.data.questionnaireInfoVO.content)
        let convertList = convert(questionList)
        state.questionListOld = convertList
        fillValue(state.questionListOld, answer)
        state.questionList = showCondition(convertList)
        let listTab = []
        tabList.value = []
        state.questionList.forEach((item) => {
          listTab.push(item.name)
        })
        if (listTab && listTab.length > 0) {
          for (let i = 0; i < listTab.length; i++) {
            let obj = {
              num: i + 1,
              finished: false,
              name: listTab[i],
              borderShow: false,
              active: false
            }
            tabList.value.push(obj)
          }
          tabListFun()
        }
      }
    })
  } else {
    const params = { questionnaireId: questionnaireId.value }
    await follow_info(params).then((res) => {
      let questionList = JSON.parse(res.data.content)
      let convertList = convert(questionList)
      state.questionListOld = convertList
      state.questionInfo = res.data
      state.questionListOld.forEach((item: any) => {
        item.list.forEach((val: any) => {
          if (val.name == '年龄' && state.userInfo.patientInfo.age) {
            val.value = state.userInfo.patientInfo.age
          }
          if (val.name == '性别' && state.userInfo.patientInfo.gender) {
            val.value = state.userInfo.patientInfo.gender == '男性' ? '男' : '女'
            val.optionId = state.userInfo.patientInfo.gender == '男性' ? '0' : '1'
            val.sort = state.userInfo.patientInfo.gender == '男性' ? 'A' : 'B'
          }
        })
      })
      state.questionList = showCondition(state.questionListOld)
      let listTab = []
      tabList.value = []
      state.questionList.forEach((item) => {
        listTab.push(item.name)
      })
      if (listTab && listTab.length > 0) {
        for (let i = 0; i < listTab.length; i++) {
          let obj = {
            num: i + 1,
            finished: false,
            name: listTab[i],
            borderShow: false,
            active: false
          }
          tabList.value.push(obj)
        }
        tabListFun()
      }
    })
  }
}
const relativeCli = (index) => {
  relatives.value = index
}
// 问卷
const onChange = () => {
  state.questionList = showCondition(state.questionListOld)
}
const List_validate = () => {
  const List = state.questionList[state.tabActive].list
  const arr = []
  List.map((u) => {
    const v = validate(u)
    arr.push(v)
  })
  arr.map((v) => {
    v.item['validate'] = v.code
    if (v.code) {
      v.item['validate_message'] = v.message
    } else {
      v.item['validate_message'] = ''
    }
  })
  const f = arr.find((v) => {
    return v.code
  })
  if (f) {
    scrollId.value = ''
    nextTick(() => {
      scrollId.value = '.my-question >>> #' + f.item.id
    })
    return false
  } else {
    return true
  }
}
const nextClick = throttle(() => {
  const f = List_validate()
  if (f) {
    if (state.questionList && state.tabActive + 1 < state.questionList.length) {
      scrollId.value = ''
      tabId.value = 'scroll_' + state.tabActive
      state.tabActive++
      tabActive.value++
      nextTick(() => {
        scrollId.value = '.my-question >>> #' + state.questionList[state.tabActive].list[0].id
      })
      tabListFun()
      isClickTab.value = true // 标记为点击触发
      setTimeout(() => {
        // 副标题名称与滚动高度获取
        indexQuestionRef.value.findSubTitle().then((res) => {
          scrollXList.value = res
          state.scrollxActive = 0
          nextTick(() => {
            setTimeout(() => {
              isClickTab.value = false
            }, 300)
          })
        })
      }, 500)
    } else {
      submit()
    }
  }
}, 300)
const submit = () => {
  const params = {
    clientId: 99999999,
    patientQuestionnaireAnswerVOs: []
  }
  state.questionList.forEach((item: any) => {
    item.list.forEach((val: any) => {
      const answerModel = {
        userId: state.userInfo.userId,
        empi: state.userInfo.patientInfo.empi,
        questionId: val.id,
        questionnaireId: state.questionInfo.questionnaireId,
        relationQuestionCode: val.relationQuestionCode,
        optionId: '',
        content: '',
        extContent: val.type == '选择 + 输入' ? val.inputText : '',
        score: val.score || 0
        // sort: val.sort || ''
      }
      // 统一处理 content 为空数组的情况
      if ((val.type == '单选' && val.value) || (val.type == '输入' && val.value)) {
        const answer = {
          ...answerModel,
          optionId: val.type == '单选' && val.optionId ? String(val.optionId) : '',
          content: val.value
        }
        params.patientQuestionnaireAnswerVOs.push(answer)
      } else if (val.type == '多选' && val.value && val.value.length > 0) {
        // if (val.value && val.value.length > 0) {
        val.optionId = val.options
          .filter((item) => val.sort.includes(item.sort))
          .map((item) => item.id)
        val.score = val.options
          .filter((item) => val.sort.includes(item.sort))
          .map((item) => item.score)
        val.value.forEach((i: string, idx: number) => {
          const answer = {
            ...answerModel,
            optionId: val.optionId[idx] + '',
            content: i,
            score: val.score[idx]
          }
          params.patientQuestionnaireAnswerVOs.push(answer)
        })
        // }
        // else {
        //   const answer = {
        //     ...answerModel,
        //     optionId: '',
        //     content: '',
        //     score: ''
        //   }
        //   params.patientQuestionnaireAnswerVOs.push(answer)
        // }
      } else {
        if (val.value) {
          const answer = {
            ...answerModel,
            optionId: '',
            content: val.value
          }
          params.patientQuestionnaireAnswerVOs.push(answer)
        }
      }
    })
  })
  params.patientQuestionnaireAnswerVOs = params.patientQuestionnaireAnswerVOs.filter((item) => {
    const hasContent =
      Object.keys(item.content || {}).length > 0 ||
      (Array.isArray(item.content) && item.content.length > 0) ||
      (typeof item.content === 'string' && item.content.trim() !== '') ||
      typeof item.content === 'number'
    return hasContent
  })
  // console.log(666, params.patientQuestionnaireAnswerVOs)
  uni.showLoading({
    title: '正在提交中...',
    mask: true
  })
  questionnaire_save(params).then((res) => {
    if (res.code == 0) {
      questionnaireFollow_save_fun(res.data)
    }
  })
}
const questionnaireFollow_save_fun = (data) => {
  let itemContents = {
    questionnaireId: questionnaireId.value,
    // questionnaireId: '3c80ba12d468477f8faed2403ff76e62',
    questionnaireRecordId: data
  }
  let params = {
    ...state.questionInfoOld,
    userId: state.userInfo.userId,
    empi: state.userInfo.patientInfo.empi,
    itemContent: JSON.stringify(itemContents),
    today: true,
    isRead: true,
    id: state.id
  }
  questionnaireFollow_save(params).then((res) => {
    if (res.code == 0) {
      uni.hideLoading()
      let fromUrl = getPage(1)
      if (fromUrl.route && fromUrl.route == 'packA/pages/healthManage/index') {
        // uni.setStorageSync('followsQuestionnaireId', res.data)
        uni.showToast({
          title: '问卷提交成功',
          icon: 'none',
          duration: 2000
        })
        uni.redirectTo({
          url: '/packA/pages/healthManage/index'
        })
      } else {
        uni.showToast({
          title: '问卷提交成功',
          icon: 'none',
          duration: 2000,
          success: () => {
            setTimeout(() => {
              uni.navigateBack()
            }, 2000)
          }
        })
      }
    }
  })
}
const prev = throttle(() => {
  state.tabActive--
  tabActive.value--
  tabId.value = 'scroll_' + state.tabActive
  tabListFun()
  scrollId.value = ''
  nextTick(() => {
    scrollId.value = '.my-question >>> #' + state.questionList[state.tabActive].list[0].id
    setTimeout(() => {
      // 副标题名称与滚动高度获取
      indexQuestionRef.value.findSubTitle().then((res) => {
        scrollXList.value = res
        state.scrollxActive = 0
        setTimeout(() => {
          isClickTab.value = false
        }, 300)
      })
    }, 300)
  })
}, 300)
const tabFun = (index, item) => {
  // tab切换
  isClickTab.value = true // 标记为点击触发
  // scrollTop.value = (tabList.value[index].top && tabList.value[index].top - 90) || 0
  scrollId.value = ''
  nextTick(() => {
    state.scrollxActive = index
    scrollId.value = '.my-question >>> #' + item.item.id
    setTimeout(() => {
      isClickTab.value = false
    }, 300) // 与滚动动画时间保持一致
  })
}
const scroll = debounce(
  (e) => {
    if (state.scrollxActive <= 0) {
      // 在未显示tab并且 currentTab <= 0时，防止uview ui抖动bug，设置默认复位值
      state.scrollxActive = 0
    }
    nextTick(() => {
      if (isClickTab.value) return // 点击触发时不处理
      // 原有的激活状态计算逻辑
      const scrollTop = e.detail.scrollTop
      const list = scrollXList.value
      let activeIndex = 0

      // 找到第一个 top 值大于滚动位置 + 偏移量的元素，取其前一个索引
      for (let i = 0; i < list.length; i++) {
        if (list[i].top > scrollTop + 100) {
          // 100 为偏移量，根据实际情况调整
          activeIndex = i > 0 ? i - 1 : 0
          break
        }
        // 处理滚动到底部的情况
        if (i === list.length - 1) activeIndex = i
      }
      state.scrollxActive = activeIndex
    })
  },
  20,
  ''
)
const scrollX = debounce(
  (e) => {
    scrollLeft.value = e.detail.scrollLeft
  },
  200,
  ''
)
</script>

<style lang="scss" scoped>
.cf {
  zoom: 1;
}

.cf::after {
  display: block;
  height: 0;
  clear: both;
  font-size: 0;
  visibility: hidden;
  content: '.';
}

.wrap {
  min-height: 100vh;
  // padding-bottom: 32rpx;
  background: #f3f7f8;

  .scroll-X {
    width: calc(100% - 64rpx);
    padding: 24rpx 32rpx;
    overflow-x: scroll;
    background: #fff;
    .headerUl {
      white-space: nowrap;
      padding: 16rpx 0;

      .item {
        width: 25%;
        text-align: center;
        display: inline-block;
        vertical-align: middle;
        font-size: 24rpx;
        color: #999;
        position: relative;

        .num {
          width: 36rpx;
          height: 36rpx;
          line-height: 36rpx;
          background: #f3f7f8;
          font-weight: 600;
          color: #999;
          border-radius: 50%;
          display: block;
          margin: 0 auto;
        }
        .img {
          width: 20rpx;
          height: 20rpx;
          background: #f3f7f8;
          border-radius: 50%;
          display: block;
          margin: 0 auto;
          padding: 4px;
        }
        .name {
          text-align: center;
          margin-top: 16rpx;
        }
        .border {
          position: absolute;
          width: 72%;
          height: 1px;
          background: #e5e6eb;
          top: 18rpx;
          left: 64%;
          &.on {
            background: #00d1b6;
          }
        }
        &.on {
          .num {
            background: #00d1b6;
            color: #fff;
          }
          .name {
            color: #00d1b6;
          }
        }
      }
    }
  }
  .relatives {
    padding: 24rpx 16rpx;
    overflow-x: auto;
    .relativesWrap {
      white-space: nowrap;
      width: 100%;
      .item {
        display: inline-block;
        vertical-align: middle;
        padding: 10rpx 24rpx;
        font-size: 26rpx;
        color: #222;
        background: #fff;
        margin-left: 16rpx;
        border-radius: 70rpx;
        &:nth-last-child(1) {
          margin-right: 32rpx;
        }
        &.on {
          color: #fff;
          background: #00d1b6;
        }
      }
    }
  }
  .questionWrap {
    height: calc(100vh - 220rpx);
    background: #fff;
    width: calc(100% - 64rpx);
    margin: 32rpx auto 0;
    border-radius: 16rpx;
    // overflow-y: auto;
    padding: 32rpx 0;
    &.on {
      height: calc(100vh - 360rpx);
    }
    .scroll-Y {
      height: 100%;
    }
  }
  .fixed {
    position: fixed;
    width: 100%;
    bottom: 0;
    left: 0;
    z-index: 10;
    padding: 24rpx 32rpx;
    padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
    box-sizing: border-box;
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    gap: 24rpx;
    &.on {
      gap: 0;
    }
    .pre_btn {
      background: #ffffff;
      width: 100%;
      border-radius: 44rpx;
      font-weight: 500;
      font-size: 32rpx;
      border: 1rpx solid #00d1b6;
      color: #00d1b6;
    }
    .next_btn {
      width: 100%;
      background: #00d1b6;
      border-radius: 44rpx;
      font-weight: 500;
      font-size: 32rpx;
      color: #ffffff;
    }
  }
}
</style>
